package com.ruoyi.web.controller.common;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author: 何建文
 * @create: 2022-05-15 13:38
 * @description:
 **/
@Controller
@RequestMapping("/upload")
public class UploadImgController {

    private static final Logger log = LoggerFactory.getLogger(UploadImgController.class);

    @RequestMapping(value = "/img", method = {RequestMethod.POST})
    @ResponseBody
    public String uploadSummerNoteImgs(@RequestParam("file") MultipartFile file) {
        // 文件保存路径，自定义路径
        String filePath = RuoYiConfig.getUploadPath();
        // 保存文件，返回文件访问地址
        return saveImg(file, filePath);
    }

    /**
     * 功能描述：png格式文件上传
     *
     * @param file
     * @param path 文件上传基础磁盘目录
     * @return 上传文件保存后的目录
     */
    public static String saveImg(MultipartFile file, String path) {
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 重新生成文件名，包含了文件上传日期
                String filename = FileUploadUtils.extractFilename(file);
                String completedPath = path + "/" + filename;
                // 转存文件
                File imgFile = new File(completedPath);
                File parentFile = imgFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                file.transferTo(imgFile);
                String imgRequestUrl = "http://localhost/profile/upload/" + filename;
                log.info("img request url:{}", imgRequestUrl);
                return imgRequestUrl;
            } catch (Exception e) {
                log.error("图片上传失败", e);
            }
        }
        return null;
    }
}
